/*
 * Copyright (C) 2016 MC
 * All rights reserved.
 *
 * $$File: $$
 * $$DateTime: $$
 * $$Author: $$
 * $$Revision: $$
 */
 
package com.glela.platform.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.cf.model.v20151127.CfAccountQueryRequest;
import com.aliyuncs.cf.model.v20151127.CfAccountQueryResponse;
import com.aliyuncs.cf.model.v20151127.CfAccountQueryResponse.AccountQueryResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.X509TrustAll;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.glela.common.util.Config;
import com.glela.platform.service.UserService;

/**
 * @author liujie
 *
 */
public class AliQueryUtil{
	
	// 以下三个常量应该放到常量类中
    public final static String  RISK_LEVEL_REJECT = "reject";
    public final static String  RISK_LEVEL_REVIEW = "review";
    public final static String  RISK_LEVEL_PASS   = "pass";
    public final static String  RISK_LEVEL_UNKNOWN   = "unknown";//未知
    //场景
    public final static String  SCENE_LOGIN = "login";
    public final static String  SCENE_ACTIVITY = "activity";
    public final static String  SCENE_REGISTER = "register";
	public final static String  SCENE_REGISTER_H5 = "register_h5";
	public final static String  SCENE_LOGIN_H5 = "login_h5";
	public final static String  SCENE_PAY = "pay";

    // 以下几项应该从配置文件读取
    private static final String aliyun_accesskey = Config.getString("aliyun.accesskey");        // 请替换成阿里云的accesskey
    private static final String aliyun_secret    = Config.getString("aliyun.secret");        // 请替换成阿里云的secret
    // afs
    private static final String afs_appkey       = Config.getString("afs.appkey");  //应用标识，不可更改
    private static final String afs_accesskey    = Config.getString("afs.accesskey"); //应用标识，不可更改
    
    private static Logger logger = LoggerFactory.getLogger(AliQueryUtil.class);
    
    public static void main(String[] args){
		System.out.println(isBlack("221.133.242.138", "18307213652", "pay", null));
	}
    public static Boolean isBlack(String remoteIp, String phoneNum, String sceneId, UserService service)  {
        
		String tokenId=UUID.randomUUID().toString();
       
        String riskLevel = null;
        try {
        	riskLevel = doAccountQueryRequest(tokenId, phoneNum, remoteIp, sceneId);
        	if(service != null) {
        		service.insertIpQueryLog(phoneNum,remoteIp, sceneId,riskLevel);
        	}
        } catch (Exception e) {
        	logger.error("isBack error. param:"+remoteIp+","+phoneNum+","+sceneId,e);
        	return null;
        }

        if (RISK_LEVEL_PASS.equals(riskLevel)) {
         	 // 请继续做注册、登陆等业务处理
            // 如注册成功写数据库，登陆成功写session等
        	return false;
        } else if (RISK_LEVEL_REVIEW.equals(riskLevel)) {
            // 可以给这个客户打个标记、或者来个验证，给他点门槛吧
        	return true;
        } else if (RISK_LEVEL_REJECT.equals(riskLevel)) {
            // 可以给这个客户打个标记、或者直接让他重新再来一次请求吧
        	return true;
        }
        return null;

    }

    /**
     * 风险用户查询服务
     * 
     * @param token 请求唯一id
     * @param phoneNumber 手机号码
     * @param email 邮箱
     * @param remoteIp 浏览器端IP
     * @param afs_SceneId 场景(register,login等)
     * @return 返回查询结果
     * @throws Exception
     */
    public static String doAccountQueryRequest(String token, String phoneNumber, String remoteIp, String afs_SceneId){
    	CfAccountQueryResponse httpResponse;
    	try {
	        IAcsClient client = null;
	        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",  aliyun_accesskey, aliyun_secret);//阿里云accesskey和secret
	        client = new DefaultAcsClient(profile);
	
	        CfAccountQueryRequest cfAccountQueryRequest = new CfAccountQueryRequest();
	        cfAccountQueryRequest.setAppKey(afs_appkey);
	        cfAccountQueryRequest.setSceneId(afs_SceneId);
	        cfAccountQueryRequest.setIp(remoteIp);
	        cfAccountQueryRequest.setPhoneNumber(phoneNumber);
	        cfAccountQueryRequest.setTrans("{}"); //非必传参数,如无特殊约定,请传入 {}
	        String timestamp = String.valueOf(System.currentTimeMillis());
	        cfAccountQueryRequest.setCFTimestamp(timestamp);
	        
	        String appToken1 = afs_appkey + "_" + afs_accesskey + "_" + timestamp;
	        cfAccountQueryRequest.setAppToken(getMD5Hex(appToken1));
	        X509TrustAll.ignoreSSLCertificate();

        	httpResponse = client.getAcsResponse(cfAccountQueryRequest);
        	
        	if (httpResponse.getSuccess()) {
        		AccountQueryResponse response= httpResponse.getAccountQueryResponse();
        		return response.getRiskLevel();
        	}
        	logger.error(httpResponse.getSuccess() + httpResponse.getMessage());// 详见错误码描述
     	} catch (ClientException e) {
       	 	logger.error("调用阿里服务发生异常: ", e);
     	}
    	return RISK_LEVEL_UNKNOWN;
    }
    
    /**
     * @param str
     * @return
     */
    public static String getMD5Hex(String str) {
        MessageDigest md = null;
        StringBuffer sb = new StringBuffer();
        byte[] tmpByte = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
        }
        md.update(str.getBytes());
        tmpByte = md.digest();
        for (int i = 0; i < tmpByte.length; ++i) {
            if ((tmpByte[i] & 0xFF) < 16) {
                sb.append("0");
            }
            sb.append(Long.toString(tmpByte[i] & 0xFF, 16));
        }
        return sb.toString();
    }

}
